package com.cloudpivot.receivales.ding.scenegroup.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.cloudpivot.receivales.contract.domain.NormalReturn;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.ding.scenegroup.domain.*;
import com.cloudpivot.receivales.ding.scenegroup.service.CrmDingService;
import com.cloudpivot.receivales.ding.scenegroup.service.ScenegroupService;
import com.cloudpivot.receivales.ding.util.DingCallbackCrypto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * 群相关 接口
 */
@Controller
@Slf4j
@RequestMapping("/saleapi/scenegroup")
public class ScenegroupController {

    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;
    @Autowired
    private ScenegroupService scenegroupService;
    @Autowired
    private CrmDingService crmDingService;

    @Value("${dingcallback.aes}")
    private String AES;
    @Value("${dingcallback.token}")
    private String TOKEN;
    @Value("${dingcallback.appkey}")
    private String APPKEY;
    @Value("${dingcallback.sleeptime}")
    private String SLEEPTIME;

    /**
     * 每刻
     */
    @Value("${myprops.maycururl}")
    private String MAYCURURL;

    /**
     * crm 推送 创建场景群
     *
     * @param entity
     */
    @PostMapping("/createByCrm")
    @ResponseBody
    public RspDTO createScenegroupByCrm(@Validated @RequestBody ScenegroupDTO entity) {
        log.info("请求（CRM）创建场景群对象：{}", JSONObject.toJSONString(entity));
        //创建场景群功能暂停
        return new RspDTO(-99);
        //验证crm记录
//        String crmguid = entity.getCrmTaskId();
//        TaskManagerDTO tmdto = crmDingService.getManagerTaskByGuid(crmguid);
//        if (Objects.isNull(tmdto) || StringUtils.isNotBlank(tmdto.getNew_scenegroupid())) {
//            //没有crm卡片
//            return new RspDTO(-101);
//        }
//        //创建场景群
//        RspDTO rsp = scenegroupService.createScenegroupByCrm(entity);
//        if (rsp.getCode() != 1) {
//            return rsp;
//        }
//        String openSceneGroupId = rsp.getData().get("openConverstaionId").toString();
//        log.info("新建的场景群ID：{}", openSceneGroupId);
//        //等待3s后创建互动卡片
//        try {
//            Thread.sleep(Integer.valueOf(SLEEPTIME));
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//            return new RspDTO(-201);
//        }
//
//        //创建群推送互动卡片
//        // 1.转换
//        InteractiveCardDTO carddto = crmDingService.convertInteractiveCardDTO(tmdto, openSceneGroupId);
//        // 2. 新建卡片 返回{"result":{"processQueryKey":"lJSgigP1gb4GWRZafRakNP9KFpp4myMfcvS1R6bHmH4="},"success":true}
//        String queryKey = scenegroupService.createInteractiveCard(carddto);
//        if (StringUtils.isBlank(queryKey)) {
//            return new RspDTO(-102);
//        }
//
//        return rsp;

    }

    /**
     * 群信息 回调接受接口
     */
    @PostMapping("/callBack")
    @ResponseBody
    public Map<String, String> callBack(@RequestParam(value = "msg_signature", required = false) String msg_signature, @RequestParam(value = "timestamp", required = false) String timeStamp, @RequestParam(value = "nonce", required = false) String nonce, @RequestBody JSONObject entity) {
        try {
            log.info("获取到的entity---{}", JSONObject.toJSONString(entity));
            String encrypt = entity.getString("encrypt");
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(TOKEN, AES, APPKEY);
            //解码请求
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encrypt);
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            String eventType = eventJson.getString("EventType");

            if ("check_url".equals(eventType)) {
                log.info("验证 回调url是否正确");
            } else if ("chat_add_member".equals(eventType)) {
                log.info("群会话 添加成员");
            } else if ("chat_remove_member".equals(eventType)) {
                log.info("群会话 删除成员");
            } else if ("chat_update_owner".equals(eventType)) {
                log.info("群会话 更换群主");
            } else if ("chat_update_title".equals(eventType)) {
                log.info("群会话 更换群名称");
            }

            return getSuccess();
        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 钉钉回调地址是否正确的加密success方法
     */
    private Map<String, String> getSuccess() {
        try {
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(TOKEN, AES, APPKEY);
            return callbackCrypto.getEncryptedMap("success");
        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 注册互动卡片回调地址
     */
    @PostMapping("/registerCardCallBack")
    @ResponseBody
    public String registerCardCallBack(@RequestBody JSONObject entity) {
        String url = null;
        Boolean flag = null;
        if (StringUtils.isNotBlank(entity.getString("url"))) {
            url = entity.getString("url");
            flag = entity.getBoolean("flag");
            scenegroupService.registerInteractiveCardCallBack(url, flag);
            return "注册成功";
        } else {
            return "参数异常";
        }
    }

    /**
     * 互动卡片回调接口
     */
    @PostMapping("/cardCallBack")
    @ResponseBody
    public void cardCallBack(@RequestBody JSONObject entity) {
        log.info("互动卡片回调对象：{}", JSONObject.toJSONString(entity));

        //crm确认互动卡片来源
        JSONObject jsonContent = JSONObject.parseObject(entity.getString("content"));
        String userId = entity.getString("userId");
        String outTrackId = entity.getString("outTrackId");
        JSONObject cardInfo = new JSONObject();
        cardInfo.put("userId", userId);
        cardInfo.put("outTrackId", outTrackId);

        JSONObject jsonPrivateData = jsonContent.getJSONObject("cardPrivateData");
        JSONObject jsonParams = jsonPrivateData.getJSONObject("params");
        log.info("互动卡片回调触发按钮{}", jsonPrivateData);
        log.info("互动卡片回调触发参数{}", jsonParams);
        scenegroupService.callbackInteractiveCard(jsonParams, cardInfo);
    }

    /**
     * 推送 项目跳转链接卡片到群中
     *
     * @param entity
     */
    @PostMapping("/pushProjectCard")
    @ResponseBody
    public String pushProjectCard(@RequestBody ProjectShowDTO entity) {
        log.info("推送 项目跳转卡片对象：{}", JSONObject.toJSONString(entity));

        String openid = entity.getOpenid();
        //转换
        InteractiveCardDTO cardEntity = crmDingService.convertToProjectShowDTO(entity, openid);
        //推送到群中
        String ret = scenegroupService.createInteractiveCard(cardEntity);

        return ret;
    }

    /**
     * 推送 项目跳转链接卡片到群中
     *
     * @param entity
     */
    @PostMapping("/pushUrlNormalCard")
    @ResponseBody
    public RspDTO pushUrlNormalCardByCrmUserId(@Validated @RequestBody UrlCardDTO entity) {
        log.info("推送 项目跳转卡片对象：{}", JSONObject.toJSONString(entity));
        //crmuserid 转 dinguserid
        String groupuser = "";
        String covmainidUrl = String.format("%s", "http://172.17.100.14:8989/systemBase/getDingUserByCrmId");
        JSONObject mainId = new JSONObject();
        mainId.put("ids", entity.getUserArray());
        try {
            String userRet = httpAPIServiceForDing.doPost(covmainidUrl, mainId.toJSONString(), null);
            JSONObject usersRet = JSONObject.parseObject(userRet);
            if (usersRet.getInteger("code") == 1) {
                groupuser = usersRet.getString("msg");
                entity.setUserArray(groupuser);
            } else {
                return new RspDTO(-100);
            }
            //转换
            InteractiveCardDTO cardEntity = crmDingService.convertToUrlCardDTO(entity);
            //推送卡片到个人
            String ret = scenegroupService.createInteractiveUncallbackCard(cardEntity);
            return new RspDTO(10);
        } catch (Exception e) {
            e.printStackTrace();
            return new RspDTO(-100);
        }
    }

    /**
     * 推送 客户生日提醒卡片到销售工程师
     *
     * @param entity
     */
    @PostMapping("/pushCusBrithdayCard")
    @ResponseBody
    public RspDTO pushCusBrithdayCardByCrmUserId(@Validated @RequestBody BirthdayCardDTO entity) {
        log.info("推送 客户生日提醒卡片：{}", JSONObject.toJSONString(entity));
        //crmuserid 转 dinguserid
        if (entity.getUserType().equals("crm")) {
            String groupuser = "";
            String covmainidUrl = String.format("%s","http://172.17.100.14:8989/systemBase/getDingUserByCrmId");
            JSONObject mainId = new JSONObject();
            mainId.put("ids", entity.getUserArray());
            try {
                String userRet = httpAPIServiceForDing.doPost(covmainidUrl, mainId.toJSONString(), null);
                JSONObject usersRet = JSONObject.parseObject(userRet);
                if (usersRet.getInteger("code") == 1) {
                    groupuser = usersRet.getString("msg");
                    entity.setUserArray(groupuser);
                } else {
                    return new RspDTO(-100);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new RspDTO(-100);
            }
        }
        //转换
        InteractiveCardDTO cardEntity = crmDingService.convertToBrithdayCardDTO(entity);
        //推送卡片到个人
        String ret = scenegroupService.createInteractiveUncallbackCard(cardEntity);
        return new RspDTO(11);

    }

    /**
     * 群机器人回调接口
     *
     * @param entity
     */
    @PostMapping("/groupRobotCallBack")
    public void groupRobotCallBack(@RequestBody JSONObject entity) {
        log.info("群机器人 回调对象:{}", JSONObject.toJSONString(entity));
        //先做 简单回复
        GroupRobotDTO groupRobotDTO = new GroupRobotDTO();
        groupRobotDTO.setTargetOpenConversationId(entity.getString("conversationId"));
        groupRobotDTO.setMsgTemplateId("inner_app_template_markdown");
        groupRobotDTO.setIsAtAll(false);
        groupRobotDTO.setRobotCode(entity.getString("robotCode"));
        JSONObject content = entity.containsKey("text") ? entity.getJSONObject("text") : null;
        if (Objects.isNull(content)) {
            JSONObject msgTemp = new JSONObject();
            msgTemp.put("markdown_content", "请输入你要提问的信息！！！");
            msgTemp.put("title", "机器人的提醒");
            groupRobotDTO.setMsgParamMap(msgTemp.toJSONString());
            scenegroupService.sendMsgByGroupRobot(groupRobotDTO);
        } else {
            JSONObject msgTemp = new JSONObject();
            msgTemp.put("markdown_content", "收到用户的信息，在\"" + entity.getString("conversationTitle") + "\"群内，发送给机器人的\"" + content.getString("content") + "\"信息");
            msgTemp.put("title", "机器人的提醒");
            groupRobotDTO.setMsgParamMap(msgTemp.toJSONString());
            scenegroupService.sendMsgByGroupRobot(groupRobotDTO);
        }
    }

    @GetMapping("/testsleepapi")
    @ResponseStatus(code = HttpStatus.OK)
    public void testapi(@RequestParam String pa) {
        //延迟
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(3000);
                System.out.println(pa + "-" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public NormalReturn exceptionHandler(MethodArgumentNotValidException e) {
        NormalReturn resultJson = new NormalReturn(-1, "error");
        resultJson.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return resultJson;
    }

}
